#coding=utf-8
#LightCam SSH抓数据程序测试版
#init by monitor 20150901

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo,threading

def oper(this):
	jsonname=this['jsonname']
	database=this['database']
	tablename=this['tablename']
	directory=this['directory']
	detailed=int(this['detailed'])
	destination=this['destination']
	print directory
	
	try:
		if detailed==0:
			line=getData(database,tablename,{'_id':{'$ne':0}})
			print line
			file=open(lchome+"/pyweb/static/json/"+directory+"/"+jsonname+".json",'w')
			file.write(line)
		else: 
			line=getData(database,tablename,{'Agent':destination})
			print line
			file=open(lchome+"/pyweb/static/json/"+directory+"/"+destination+".json",'w')
			print lchome+"/pyweb/static/json/"+directory+"/"+destination+".json"
			file.write(line)
			#json.dumps(items,file)
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()


def getData(dbname,tablename,expr):
	dboper=db.useDatabase(dbname)
	tableoper=db.UseCollection(dboper,tablename)
	sortcont=[("_id",pymongo.ASCENDING)]
	opts=db.queryData(tableoper,expr,sortcont,0)
	jdata={}
	jdata['rows']=[]
	for line in opts:
		sdata={}
		for key,value in line.items():
			if key=='_id':
				continue
			sdata[key]=value
		jdata['rows'].append(sdata)
	return json.dumps(jdata)
	
if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	agent_hostname=lc_libs.lc_gethostname()

	#初始化数据库
	
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

	db.connect()
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)

	MonitorList = []

	for lines in open(confname):
		if lines[0] == '#' or lines.split("\t")[0] not in (agent_hostname,'default'):
			continue

		line=lines.strip('\r\n').split('\t')
		dconf={}
		
		for t in line[3].split(","):
			dconf['agent_hostname']=line[0]
			dconf['destination']=line[1]
			dconf['jsonname']=t
			dconf['database']=line[4]
			dconf['detailed']=line[5]
			dconf['interval']=line[6]
			dconf['schedule']=line[7]
			dconf['holiday']=line[8]
			if int(dconf['detailed'])==1:
				dconf['tablename']='oramon_'+t
				dconf['directory']=line[2]+dconf['tablename']
			else:
				dconf['tablename']=t
				dconf['directory']=line[2]
			MonitorList.append(dconf)
			dconf={}


	timeflag=int(time.time())


	
	while True:
		time.sleep(1)
		timeflag+=1
		realtime=int(time.time())

		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())

		threads = []
	
		for i in MonitorList:
			print i
			holiday_state = lc_libs.lc_isholiday()
			if int(i['holiday']) == 1 and holiday_state == True:
				continue
				
			time_state = lc_libs.lc_schedule(i['schedule'])
			if time_state == False:
				continue
			
			flag=realtime%int(i['interval'])
			if flag<=realtime-timeflag:
				t = threading.Thread(target=oper,args=(i,))
				threads.append(t)
		
		timeflag=int(time.time())
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.1)
				if(len(threading.enumerate()) < 10):
					break
